<?php
namespace Apps\Csoap\Controllers;

use Phalcon\Mvc\Controller;
use PhalconPlus\Common\ResponseResultStatus;
use PhalconPlus\Common\Util;

class BaseController extends Controller
{
    //业务数据
    private $data;
    private  $token;
    
    public function initialize()
    {
        $this->token ='thebossawageincrease';

        if (!$this->validateSignature($this->token)) {
             $this->sendResult(ResponseResultStatus::SIGN_ERROR,'','签名错误');exit;
        }
        else{
            $this->data = json_decode($this->request->getPost('data'),TRUE);
        }
    }
    
    protected function getDataItem($key, $defaultValue=null)
    {
        return $this->data && isset($this->data[$key]) ? $this->data[$key] : $defaultValue;
    }
    
    protected function senderror( $status=null, $errmsg=null)
    {
        $this->sendResult( $status,'', $errmsg);
        return false;
    }
    
    protected function sendResult($status=null, $result=null,$errmsg=null, $timestamp=null,$nonce=null,$sign=null) {

        $status = $status === null ? ResponseResultStatus::ERROR : $status;
        $result = $result === null ? '' : $result;
        $timestamp = $timestamp === null ? time() : $timestamp;
        $nonce = $nonce === null ? Util::RandStr(12) : $nonce;
        $sign = $sign === null ? $this->getSign($this->token, $timestamp, $nonce) : $sign;
        $this->errmsg = $errmsg === null ? '错误信息' : $errmsg;
        $data = [
            'status' => $status,
            'result' => $result,
            'errmsg' => $errmsg,
            'timestamp' => $timestamp,
            'nonce' => $nonce,
            'sign' => $sign
        ];
        echo json_encode($data);exit;
    }
    
    
    /**
     * 判断验证请求的签名信息是否正确
     *
     * @param  string $token 验证信息
     * @return boolean
     */
    private function validateSignature($token) {
        $req = $this->request;
        $sign = $req->getPost('sign');
        $timestamp = $req->getPost('timestamp');
        $once = $req->getPost('nonce');
        return $this->getSign($token, $timestamp, $once) == $sign;
    }
    /**
     * 生成签名
     * @date: 2016年2月24日 
     * @author: 545
     */
    private function getSign($token,$timestamp,$once){
        $signatureArray = array($token, $timestamp, $once);
        return sha1(implode($signatureArray));
    }
    
}